// 230. 二叉搜索树中第K小的元素

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function kthSmallest(root: TreeNode | null, k: number): number {
  const stack = [];

  //    当根节点或者栈中存在内容循环继续
  while (root || stack.length) {
    // 先遍历左节点
    while (root) {
      stack.push(root);
      root = root.left;
    }
    //栈顶元素是最小的
    root = stack.pop();
    k--;
    // 如果k为0 跳出循环
    if (!k) break;
    // 左节点遍历完毕 遍历右节点
    root = root.right;
  }

  return root.val;
}
